import React from 'react'
import {List,Badge} from 'antd-mobile'
import {connect} from 'react-redux'

const Item = List.Item
const Brief = Item.Brief

@connect(
    state => state
)
class Msg extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            msgList: []
        }
    }

    getLastMsg(arr) {
        return arr[arr.length - 1]
    }

    render() {
        if (this.props.chatmsg.chatMsgList.length == 0) {
            return null;
        }
        let tempMsgList = {};
        for (let item of this.props.chatmsg.chatMsgList) {
            if (tempMsgList[item.chatid]) {
                tempMsgList[item.chatid].push(item);
            } else {
                tempMsgList[item.chatid] = []
                tempMsgList[item.chatid].push(item);
            }
        }
        //分组并按照时间戳进行排序
        const chatList = Object.values(tempMsgList).sort((a,b)=>{
              const a_last = this.getLastMsg(a).create_time;
              const b_last = this.getLastMsg(b).create_time;
              console.log(a_last,b_last)
              return b_last - a_last
        });
        return (
            <div>
                <List className="my-list">
                    {chatList.map((item) => {
                        const lastItem = this.getLastMsg(item);
                        const chatObj = this.props.user._id == lastItem.from ? lastItem.to : lastItem.from
                        const avarter = this.props.chatmsg.userlist[chatObj].avatar
                        return <Item
                            arrow="horizontal"
                            thumb={require(`../img/${avarter}.png`)}
                            multipleLine
                            key={lastItem._id}
                            extra={<Badge text={
                                item.filter(v=>v.from!=this.props.user._id&&!v.read).length
                            }></Badge>}
                            onClick={() => {
                                this.props.history.push(`/chat/${chatObj}`)
                            }}
                        >
                            {this.props.chatmsg.userlist[chatObj].name}
                            <Brief>{lastItem.content}</Brief>
                        </Item>
                    })}
                </List>
            </div>
        );
    }
}

export default Msg
